package com.shopmall.goods.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.shopmall.goods.dao.GoodsAttrValueMapper;
import com.shopmall.goods.dao.GoodsInfoMapper;
import com.shopmall.goods.entity.GoodsAttrValue;
import com.shopmall.goods.entity.GoodsInfo;
import com.shopmall.goods.service.GoodsInfoService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class GoodsInfoServiceImpl extends ServiceImpl<GoodsInfoMapper, GoodsInfo> implements GoodsInfoService {
    @Autowired
    private GoodsAttrValueMapper goodsAttrValueMapper;
    @Override
    public IPage<GoodsInfo> pageList(GoodsInfo goodsInfo) {
        IPage<GoodsInfo> page = new Page<>(goodsInfo.getPageNum(),goodsInfo.getPageSize());
        LambdaQueryWrapper<GoodsInfo> wrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(goodsInfo.getGoodsName())){
            wrapper.eq(GoodsInfo::getGoodsName,goodsInfo.getGoodsName());
        }
        IPage<GoodsInfo> p = this.baseMapper.selectPage(page, wrapper);
        return p;

    }
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    ElasticsearchClient elasticsearchClient;
    @Override
    public int addOrUpdate(GoodsInfo goodsInfo) {
        if(goodsInfo.getId()==null){
            int insert = this.baseMapper.insert(goodsInfo);
            Integer id = goodsInfo.getId();
            List<GoodsAttrValue> goodsAttrValueList = goodsInfo.getGoodsAttrValueList();
            if(goodsAttrValueList!=null){
                for (GoodsAttrValue goodsAttrValue : goodsAttrValueList) {
                    goodsAttrValue.setGoodsId(id);
                    goodsAttrValueMapper.insert(goodsAttrValue);
                }
            }
            return insert;
        }else{
            goodsAttrValueMapper.delete(new LambdaQueryWrapper<GoodsAttrValue>().eq(GoodsAttrValue::getGoodsId,goodsInfo.getId()));
            List<GoodsAttrValue> goodsAttrValueList = goodsInfo.getGoodsAttrValueList();
            if(goodsAttrValueList!=null){
                for (GoodsAttrValue goodsAttrValue : goodsAttrValueList) {
                    goodsAttrValue.setGoodsId(goodsInfo.getId());
                    goodsAttrValueMapper.insert(goodsAttrValue);
                }
            }
            int i = this.baseMapper.updateById(goodsInfo);
            if(i>0){
                String s = JSON.toJSONString(goodsInfo);
                //发送消息
//                rabbitTemplate.convertAndSend("76_exchange","routingKey",s);
            }
            return this.baseMapper.updateById(goodsInfo);
        }

    }

    @Override
    public int deleteById(Integer id) {
        goodsAttrValueMapper.delete(new LambdaQueryWrapper<GoodsAttrValue>().eq(GoodsAttrValue::getGoodsId,id));
        return baseMapper.deleteById(id);
    }

    @Override
    public List<GoodsInfo> getGoods() {
        return baseMapper.selectList(null);
    }

    @Override
    public List<GoodsInfo> getGoodsById(List<Integer> id) {
        QueryWrapper<GoodsInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(GoodsInfo::getId,id);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public Map<String,  Object> frontIndex(Integer type, Integer limit, Integer page) {
        Page<GoodsInfo> page1 = new Page<>(page,limit);
        QueryWrapper<GoodsInfo> query = new QueryWrapper<>();
        query.lambda()
                .eq(GoodsInfo::getStatus,1)
                .like(GoodsInfo::getRecommend, type);

        List<GoodsInfo> records = baseMapper.selectPage(page1, query).getRecords();
        records.forEach(item->{
            QueryWrapper<GoodsAttrValue> queryWrapper =  new QueryWrapper<>();
            queryWrapper.lambda().eq(GoodsAttrValue::getGoodsId, item.getId());
            item.setGoodsAttrValueList(goodsAttrValueMapper.selectGoodsAttrValueList(item.getId()));
        });
        Map<String,  Object> map = new HashMap<>();
        map.put("total",page1.getTotal());
        map.put("page",page1.getPages());
        map.put("totalPage", 0);
        return map;
    }

    @Override
    public Map<String, Object> frontDetail(Integer id, String type) {
        //商品
        GoodsInfo goodsInfo = getById(id);
        //商品规格集合
        List<GoodsAttrValue> list = goodsAttrValueMapper.selectGoodsAttrValueList(id);
        GoodsAttrValue goodsAttrValueDt = list.get(0);
        Map<String,Object> map = new HashMap<>();
        map.put("activityAllH5",null);
        map.put("priceName",null);
        List<Map<String,Object>> productAttrs = new ArrayList<>();
        for (GoodsAttrValue goodsAttrValue: list) {
            Map<String,Object> mp = (Map<String, Object>) JSON.parse(goodsAttrValue.getAttrValue());
            for (String key : mp.keySet()) {
                Map<String,Object> productAttr = new HashMap<>();
                productAttr.put("attrName",key);
                productAttr.put("attrValues",mp.get(key));
                productAttr.put("productId",id);
                productAttr.put("type",0);
                productAttr.put("isDel",false);
                productAttrs.add(productAttr);
            }
        }
        productAttrs = processMapList(productAttrs);
        map.put("productAttr",productAttrs);
        Map<String,Object> productInfo = new HashMap<>();
        productInfo.put("vipPrice",goodsAttrValueDt.getOtPrice());
        productInfo.put("videoLink",null);
        productInfo.put("version",null);
        productInfo.put("unitName",goodsInfo.getUnit());
        productInfo.put("tempId",0);
        productInfo.put("storeName",goodsInfo.getGoodsName());
        productInfo.put("storeInfo",goodsInfo.getDescText());
        productInfo.put("stock",goodsAttrValueDt.getStock());
        Integer specType = list.size()>1?1:0;
        productInfo.put("specType",specType);
        productInfo.put("soureLink","");
        productInfo.put("sort",goodsInfo.getSort());
        productInfo.put("sliderImage",goodsInfo.getBannerImage());
        productInfo.put("sales",goodsAttrValueDt.getSales());
        productInfo.put("price",goodsAttrValueDt.getOtPrice());
        productInfo.put("postage",0);
        productInfo.put("otPrice",goodsAttrValueDt.getOtPrice());
        productInfo.put("merUse",0);
        productInfo.put("merId",0);
        productInfo.put("keyword","");
        productInfo.put("isSub",false);
        productInfo.put("isShow", "1".equals(goodsInfo.getStatus()));
        productInfo.put("isSeckill",false);
        productInfo.put("isRecycle",false);
        productInfo.put("isPostage",true);
        productInfo.put("isNew",true);
        productInfo.put("isHot",true);
        productInfo.put("isGood",true);
        productInfo.put("isDel",false);
        productInfo.put("isBest",true);
        productInfo.put("isBenefit",true);
        productInfo.put("isBargain",false);
        productInfo.put("image","http://localhost:8080/profile/"+goodsInfo.getTitleImage());
        productInfo.put("id",goodsInfo.getId());
        productInfo.put("flatPattern",goodsAttrValueDt.getImage());
        productInfo.put("ficti",goodsAttrValueDt.getSales());
        productInfo.put("cost",goodsAttrValueDt.getCost());
        productInfo.put("content",goodsInfo.getGoodsDetail());
        productInfo.put("codePath",null);
        productInfo.put("giveIntegral",goodsInfo.getPoints());
        productInfo.put("cateId",null);
        productInfo.put("browse",0);
        productInfo.put("barCode","");
        productInfo.put("addTime",null);
        productInfo.put("activity",null);
        map.put("productInfo",productInfo);
        Map<String,GoodsAttrValue> productValue = new HashMap<>();
        for (GoodsAttrValue goodsAttrValue : list) {
            goodsAttrValue.setGoodsId(goodsAttrValue.getGoodsId());
            Map<String,Object> mp = (Map<String, Object>) JSON.parse(goodsAttrValue.getAttrValue());
            StringBuilder k = new StringBuilder();
            for (String key : mp.keySet()) {
                if (k.isEmpty()){
                    k = new StringBuilder(String.valueOf(mp.get(key)));
                }else {
                    k.append(",").append(mp.get(key));
                }
            }
            productValue.put(k.toString(),goodsAttrValue);
        }
        map.put("productValue",productValue);
        return map;
    }

    private List<Map<String, Object>> processMapList(List<Map<String, Object>> productAttrs) {
        Map<String, StringBuilder> attrNameToValues = new HashMap<>();
        Map<String, Map<String, Object>> attrNameToMap = new HashMap<>();
        for (Map<String, Object> map : productAttrs) {
            String attrName = (String) map.get("attrName");
            String attrValues = (String) map.get("attrValues");
            if (attrNameToValues.containsKey(attrName)) {
                attrNameToValues.get(attrName).append(","+attrValues);
            } else {
                attrNameToValues.put(attrName, new StringBuilder(attrValues));
                attrNameToMap.put(attrName, new HashMap<>(map));
            }
        }
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map.Entry<String, StringBuilder> entry : attrNameToValues.entrySet()) {
            String attrName = entry.getKey();
            String combinedAttrValues = entry.getValue().toString();
            Map<String, Object> map = attrNameToMap.get(attrName);
            map.put("attrValues", combinedAttrValues);
            result.add(map);
        }
        return result;
    }


}
